package com.hanoi.wiki.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.UserDAO;
import com.hanoi.wiki.dao.UserEvaluationDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.manager.UserEvaluationManager;
import com.hanoi.wiki.model.User;
import com.hanoi.wiki.model.UserEvaluation;
import com.hanoi.wiki.model.json.UserEvaluationJson;

@Component
@Transactional
public class UserEvaluationManagerImpl extends BaseManagerImpl implements UserEvaluationManager{

	@Autowired
	private UserEvaluationDAO evaluationDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	public int save(UserEvaluationJson json) {
		try {
			UserEvaluation userEvaluation = new UserEvaluation(json);
			
			User user = userDAO.get(json.getUser());
			if(user != null) {
				userEvaluation.setUser(user);
			}
			
			return evaluationDAO.saveUserEvaluation(userEvaluation);
		} catch (DataAccessException e) {
			log.error("",e);
		}
		return 0;
	}

	public void update(UserEvaluationJson json) {
		try {
			UserEvaluation userEvaluation = new UserEvaluation(json);
			
			userEvaluation.setId(json.getId());
			User user = userDAO.get(json.getUser());
			if(user != null) {
				userEvaluation.setUser(user);
			}
			
			evaluationDAO.update(userEvaluation);
		} catch (DataAccessException e) {
			log.error("",e);
		}
	}

	public UserEvaluationJson get(Integer id) {
		try {
			return new UserEvaluationJson(evaluationDAO.get(id));
		} catch (DataAccessException e) {
			log.error("",e);
		}
		return null;
	}

	public List<UserEvaluationJson> getList() {
		List<UserEvaluationJson> userEvalJsonList = new ArrayList<UserEvaluationJson>();
		List<UserEvaluation> userEvalList = evaluationDAO.getList();
		try {
			for(UserEvaluation evaluation : userEvalList) {
				userEvalJsonList.add(new UserEvaluationJson(evaluation));
			}
		} catch (DataAccessException e) {
			log.error("",e);
		}
		return userEvalJsonList;
	}

	public void remove(Integer id) {
		try {
			if(evaluationDAO.get(id) != null) {
				evaluationDAO.remove(id);
			}
		} catch (DataAccessException e) {
			log.error("",e);
		}
		
	}

}
